/**
 * Created by lavystord on 16/12/7.
 */
import { AsyncStorage } from 'react-native';
import { mappingToSavedState } from '../store/subStore';


let isWritingState = false;
function persistStore() {
    return (dispatch, getState) => {
        if (!isWritingState) {
            const savedState = mappingToSavedState(getState());
            isWritingState = true;
            return new Promise(
                (resolve, reject) => {
                    AsyncStorage.setItem('state', JSON.stringify(savedState), (err) => {
                        if (err) {
                            console.error(`AsyncStorage set error:${err.message}`);
                            dispatch(makeError(err.message));
                        }
                        isWritingState = false;
                        resolve();
                    });
                }
            );
        }
    };
}

module.exports = {
    persistStore,
};
